package net.hn.hnms.biz.process.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import net.hn.hnms.biz.common.activiti.builder.ProcessExecutor;
//import net.hn.hnms.biz.common.activiti.builder.TaskExecutor;
//import net.hn.hnms.biz.common.activiti.result.ProcessHistoryResult;
//import net.hn.hnms.biz.common.activiti.result.ProcessTaskResult;
//import net.hn.hnms.biz.common.activiti.service.impl.ProcessService;
import net.hn.hnms.biz.api.mine.RemoteMineInfoService;
import net.hn.hnms.biz.api.mine.model.WeChartBaseMessage;
import net.hn.hnms.biz.process.domain.dto.*;
import net.hn.hnms.biz.process.domain.vo.StartWorkDataVo;
import net.hn.hnms.biz.process.mapper.StartDataMapper;
import net.hn.hnms.biz.process.mapper.StartFlowDataMapper;
import net.hn.hnms.biz.process.mapper.StartWorkFlowMapper;
import net.hn.hnms.biz.process.mapper.StartWorkMapper;
import net.hn.hnms.biz.process.service.StartProcessService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.common.satoken.utils.LoginHelper;
import net.hn.hnms.sys.system.api.model.LoginUser;
import net.hn.hnms.biz.process.domain.StartDataPo;
import net.hn.hnms.biz.process.domain.StartFlowDataPo;
import net.hn.hnms.biz.process.domain.StartWorkFlowPo;
import net.hn.hnms.biz.process.domain.StartWorkPo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: StartProcessServiceImpl
 * @Description 开工管理实现类
 * @Author 王龙
 * @Date 2022-09-24
 * @Version 0.1
 */
@Service
public class StartProcessServiceImpl implements StartProcessService {
    /**
     * 开工管理Mapper
     */
    @Resource
    private StartWorkMapper startWorkMapper;

    /**
     * 开工管理流程Mapper
     */
    @Resource
    private StartWorkFlowMapper startWorkFlowMapper;
    /**
     * 零星工程管理Mapper
     */
    @Resource
    private StartDataMapper startDataMapper;

    /**
     * 零星工程管理流程Mapper
     */
    @Resource
    private StartFlowDataMapper startFlowDataMapper;


    /**
     * 审批流程
     */
//    @Resource
//    private ProcessService processService;

    /**
     * 发送审批通知
     */
    @Resource
    private RemoteMineInfoService remoteMineInfoService;

    /**
     * 工作流查询当前任务列表
     *
     * @param businessKey
     * @return
     */
//    public List<ProcessHistoryResult> taskByid(String businessKey) {
//        ProcessExecutor processExecutor = processService.processExecutor();
//        //查询流程运行历史
//        List<ProcessHistoryResult> historyResults = processExecutor.createProcessQuery().businessKey(businessKey).processHistoryTracking();
//        return historyResults;
//    }

    /**
     * 工作流--开启流程审批
     *
     * @param businessKey
     * @param name
     * @param user
     * @return
     */
//    public ProcessTaskResult startProcess(String businessKey, String name, String user) {
//        ProcessTaskResult taskResult = processService.processExecutor().startProcess()
//                //发起人
//                .processName(name).businessKey(businessKey).applyUser(user).start();
//        //默认完成第一条发起审批
//        this.executeProcessTask(businessKey, 1, "发起审批同意", user);
//
//        return taskResult;
//    }
    /**
     * 完成任务
     *
     * @param businessKey
     * @param approve
     * @return
     */
//    public ProcessTaskResult executeProcessTask(String businessKey, Integer approve, String content, String user) {
//        TaskExecutor taskExecutor = processService.taskExecutor();
//        //查询通过businessKey查询任务参数
//        ProcessTaskResult variables = taskExecutor.createTaskVariablesQuery().businessKey(businessKey).query();
//        System.out.println(JSONUtil.toJsonPrettyStr(variables));
//
//        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
//
//        //执行任务
//        for (int i = 0; i < variables.getTasks().size(); i++) {
//            ProcessTaskResult executeResult = taskExecutor.taskId(variables.getTasks().get(i).getTaskId())
//                    .variable("approve", approve).variable("comment", approve == 0 ? content : content).executor(user).execute();
//            System.out.println(JSONUtil.toJsonPrettyStr(executeResult));
//            System.out.println("1111111111111111111111111111111111");
////            executeResult.isFinished();
//        }
//        return variables;
//    }

//    public String base(String businessKey) {
//        //输出流程运行图像Base64数据
//        ProcessExecutor processExecutor = processService.processExecutor();
//        String base64 = processExecutor.createProcessQuery().businessKey(businessKey).processImageBase64();
//        return base64;
//    }


    /**
     * 开工管理添加
     * @param startWorkPo
     * @return
     */
    @Override
    public boolean customizationAdd(StartWorkPo startWorkPo) {
        //先查工作票分类是否已经存在
        String ticketTypeId = startWorkPo.getTicketTypeId();
        List<StartWorkPo> startWorkPos = startWorkMapper.selectList(new LambdaQueryWrapper<StartWorkPo>().eq(StartWorkPo::getTicketTypeId, ticketTypeId));
        if (!startWorkPos.isEmpty()) {
            throw new HuaNengException(Constants.FAIL, "该工作票分类已经存在，请删除后再次添加");
        }


        //流程时间
        if (startWorkPo.getFlowTakeDate() == null) {
            startWorkPo.setFlowTakeDate(new Date());
        }
        //流程状态设置为零
        startWorkPo.setFlowStatus("0");
        //步骤状态设置为零
        startWorkPo.setStepState("0");

        int insert = startWorkMapper.insert(startWorkPo);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    /**
     * 开工管理修改
     * @param startWorkPo
     * @return
     */
    @Override
    public boolean customizationUpdate(StartWorkPo startWorkPo) {
        String ticketId = startWorkPo.getTicketId();
        StartWorkPo startWorkPo1 = startWorkMapper.selectById(ticketId);
        if (startWorkPo1 == null) {
            throw new HuaNengException(Constants.FAIL, "未查询到开工管理" + ticketId);
        }

        //获取请求分类分类ID
        String ticketTypeId = startWorkPo.getTicketTypeId();
        //获取数据库分类id
        String ticketTypeId1 = startWorkPo1.getTicketTypeId();
        //判断是否修改了分类ID
        if (!ticketTypeId.equals(ticketTypeId1)) {
            //如果两个分类ID不相等，那么就查询数据库该请求分类是否存在
            List<StartWorkPo> startWorkPos = startWorkMapper.selectList(new LambdaQueryWrapper<StartWorkPo>().eq(StartWorkPo::getTicketTypeId, ticketTypeId));
            //如果不为空，就代表已经存在
            if (!startWorkPos.isEmpty()) {
                throw new HuaNengException(Constants.FAIL, "此分类已存在，请修改为其他分类");
            }
        }
        int i = startWorkMapper.updateById(startWorkPo);
        if (i > 0) {
            return true;
        }
        return false;
    }

    /**
     * 开工管理批量删除
     * @param idList
     * @return
     */
    @Override
    public boolean customizationDelete(List<String> idList) {
        //开工管理删除
        int i = startWorkMapper.deleteBatchIds(idList);
        for (String s : idList) {
            //开工管理流程删除
            startWorkFlowMapper.delete(new LambdaQueryWrapper<StartWorkFlowPo>().eq(StartWorkFlowPo::getWorkTicketId, s));
        }
        if (idList.size() == i) {
            return true;
        }
        return false;
    }

    /**
     * 分页条件查询开工管理列表
     * @param pageQuery
     * @param startWorkPo
     * @return
     */
    @Override
    public ResponsePage<StartWorkPo> customizationPageList(PageQuery pageQuery, StartWorkPo startWorkPo) {
        //条件封装
        LambdaQueryWrapper<StartWorkPo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(startWorkPo.getMineCode()), StartWorkPo::getMineCode, startWorkPo.getMineCode());
        //分页查询
        Page<StartWorkPo> startWorkPoPage = startWorkMapper.selectPage(pageQuery.build(), queryWrapper);
        //判断返回数据
        if (startWorkPoPage.getRecords().isEmpty()) {
            new ResponsePage<StartWorkPo>(new ArrayList(), 0);
        }
        //封装返回数据
        ResponsePage<StartWorkPo> startWorkPoResponsePage = new ResponsePage<StartWorkPo>(startWorkPoPage.getRecords(),startWorkPoPage.getTotal());
        return startWorkPoResponsePage;
    }

    /**
     * 开工管理审批流程设置
     * @param startWorkFlowDto
     * @return
     */
    @Override
    public Boolean addApproveAdd(StartWorkFlowDto startWorkFlowDto) {
        //开工管理ID
        String workTicketId = startWorkFlowDto.getWorkTicketId();
        //开工管理实体
        StartWorkPo startWorkPo = startWorkMapper.selectById(workTicketId);
        if (startWorkPo == null) {
            throw new HuaNengException(Constants.FAIL, "开工管理ID不存在"+workTicketId);
        }
        //步骤状态(0未添加步骤，1已填加步骤)
        startWorkPo.setStepState("1");
        startWorkMapper.updateById(startWorkPo);
        //类型ID
        String ticketTypeId = startWorkPo.getTicketTypeId();
        //类型名称
        String ticketTypeName = startWorkPo.getTicketTypeName();

        // 步骤列表
        List<WorkTicketDto> procedureList = startWorkFlowDto.getProcedureList();
        int count = 0;
        for (WorkTicketDto workTicketDto : procedureList) {
            //流程
            StartWorkFlowPo startWorkFlowPo = new StartWorkFlowPo();
            //开工管理父ID
            startWorkFlowPo.setWorkTicketId(workTicketId);
            //工作票分类ID
            startWorkFlowPo.setTicketTypeId(ticketTypeId);
            //工作票分类名称
            startWorkFlowPo.setTicketTypeName(ticketTypeName);
            //序号列表
            startWorkFlowPo.setSerialNumbers(workTicketDto.getSerialNumbers());
            //职位ID
            startWorkFlowPo.setPositionId(workTicketDto.getPositionId());
            //职位名称
            startWorkFlowPo.setPositionName(workTicketDto.getPositionName());
            //发起人ID
            //发起人名称
            //JSON表单
            startWorkFlowPo.setJsonFrom(workTicketDto.getJsonFrom());
            //审批人ID
            startWorkFlowPo.setApproverId(workTicketDto.getApproverId());
            //审批人名称
            startWorkFlowPo.setApproverName(workTicketDto.getApproverName());
            count += startWorkFlowMapper.insert(startWorkFlowPo);
        }
        //创建工作流流程模板
       // this.createProcess(workTicketFlowDto, getLoginUserInfo());

        if (procedureList.size() == count) {
            return true;
        }
        return false;
    }

    /**
     * 根据开工管理ID获取审批序号列表
     * @param id
     * @return
     */
    @Override
    public StartWorkFlowDto approveById(String id) {
        StartWorkPo startWorkPo = startWorkMapper.selectById(id);
        if (startWorkPo == null) {
            throw new HuaNengException(Constants.FAIL, "开工管理ID不存在"+id);
        }
        LambdaQueryWrapper<StartWorkFlowPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StartWorkFlowPo::getWorkTicketId, id);
        //获取开工管理流程数据
        List<StartWorkFlowPo> startWorkFlowPos = startWorkFlowMapper.selectList(wrapper);
        if (startWorkFlowPos.isEmpty()) {
            return new StartWorkFlowDto();
        }
        //返回格式
        StartWorkFlowDto startWorkFlowDto = new StartWorkFlowDto();
        //设置开工管理父ID
        startWorkFlowDto.setWorkTicketId(id);
        //填充返回jsonfrom(模板没有还有jsonfrom)
//        startWorkFlowDto.setFromData();
        List<WorkTicketDto> collect = startWorkFlowPos.stream().map(t -> {
            WorkTicketDto workTicketDto = new WorkTicketDto();
            //开工管理审批流程模板ID
            workTicketDto.setFlowSchemeId(t.getFlowSchemeId());
            //Json表单
            workTicketDto.setJsonFrom(t.getJsonFrom());
            //职位ID
            workTicketDto.setPositionId(t.getPositionId());
            //职位Name
            workTicketDto.setPositionName(t.getPositionName());
            //审批人ID
            workTicketDto.setApproverId(t.getApproverId());
            //审批人Name
            workTicketDto.setApproverName(t.getApproverName());
            //选中的序号列表
            workTicketDto.setSerialNumbers(t.getSerialNumbers());
            return workTicketDto;
        }).collect(Collectors.toList());
        startWorkFlowDto.setProcedureList(collect);
        return startWorkFlowDto;
    }

    /**
     * 零星工程定制状态修改
     * @param id
     * @return
     */
    @Override
    public Boolean amendStatusById(String id) {
        StartWorkPo startWorkPo = startWorkMapper.selectById(id);
        if (startWorkPo == null) {
            throw new HuaNengException(Constants.FAIL, "未查询到该开工管理ID" + id);
        }
        //获取状态 开工管理状态(0启用,1禁用)
        String ticketStatus = startWorkPo.getTicketStatus();
        if ("0".equals(ticketStatus)) {
            startWorkPo.setTicketStatus("1");
        } else if ("1".equals(ticketStatus)) {
            startWorkPo.setTicketStatus("0");
        } else {
            throw new HuaNengException(Constants.FAIL,"工作票状态错误,请联系管理员");
        }
        int i = startWorkMapper.updateById(startWorkPo);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean addApproveUpdate(StartWorkFlowDto startWorkFlowDto) {
        //流程已经创建  需要删除后重建

        //开工管理ID
        String workTicketId = startWorkFlowDto.getWorkTicketId();
        //开工管理实体
        StartWorkPo startWorkPo = startWorkMapper.selectById(workTicketId);
        if (startWorkPo == null) {
            throw new HuaNengException(Constants.FAIL, "开工管理ID不存在"+workTicketId);
        }
//        //创建新的开工管理
//        startWorkMapper.insert(startWorkPo);
        //步骤状态(0未添加步骤，1已填加步骤)
//        startWorkPo.setStepState("1");
//        startWorkMapper.updateById(startWorkPo);

        //删除流程模板的记录
        LambdaQueryWrapper<StartWorkFlowPo> eq = new LambdaQueryWrapper<StartWorkFlowPo>().eq(StartWorkFlowPo::getWorkTicketId, workTicketId);
        startWorkFlowMapper.delete(eq);

        //删除工作流部署的模板




        //类型ID
        String ticketTypeId = startWorkPo.getTicketTypeId();
        //类型名称
        String ticketTypeName = startWorkPo.getTicketTypeName();

        // 步骤列表
        List<WorkTicketDto> procedureList = startWorkFlowDto.getProcedureList();
        int count = 0;
        for (WorkTicketDto workTicketDto : procedureList) {
            //流程
            StartWorkFlowPo startWorkFlowPo = new StartWorkFlowPo();
            //开工管理父ID
            startWorkFlowPo.setWorkTicketId(workTicketId);
            //工作票分类ID
            startWorkFlowPo.setTicketTypeId(ticketTypeId);
            //工作票分类名称
            startWorkFlowPo.setTicketTypeName(ticketTypeName);
            //序号列表
            startWorkFlowPo.setSerialNumbers(workTicketDto.getSerialNumbers());
            //职位ID
            startWorkFlowPo.setPositionId(workTicketDto.getPositionId());
            //职位名称
            startWorkFlowPo.setPositionName(workTicketDto.getPositionName());
            //发起人ID
            //发起人名称
            //JSON表单
            startWorkFlowPo.setJsonFrom(workTicketDto.getJsonFrom());
            //审批人ID
            startWorkFlowPo.setApproverId(workTicketDto.getApproverId());
            //审批人名称
            startWorkFlowPo.setApproverName(workTicketDto.getApproverName());
            count += startWorkFlowMapper.insert(startWorkFlowPo);
        }
        //创建工作流流程模板
        // this.createProcess(workTicketFlowDto, getLoginUserInfo());

        if (procedureList.size() == count) {
            return true;
        }
        return false;
    }


    /**
     * 零星工程-添加
     * @param startWorkDataDto
     * @return
     */
    @Override
    public Boolean projectAdd(StartWorkDataDto startWorkDataDto) {
        //获取开工管理主键ID
        String workTicketId = startWorkDataDto.getWorkTicketId();
        StartWorkPo startWorkPo = startWorkMapper.selectById(workTicketId);
        if (startWorkPo == null) {
            throw new HuaNengException(Constants.FAIL, "未查询到开工管理主键ID:" + workTicketId);
        }

        // 生成零星工程数据表记录
        StartDataPo startDataPo = new StartDataPo();
        //开工管理主键ID
        startDataPo.setWorkTicketId(workTicketId);
        //零星工程名称
        startDataPo.setTickDataName(startWorkDataDto.getStartTicketDataName());
        //工作票分类ID和name
        startDataPo.setTicketTypeId(startWorkPo.getTicketTypeId());
        startDataPo.setTicketTypeName(startWorkPo.getTicketTypeName());
        //开工管理名称
        startDataPo.setTickName(startWorkPo.getTicketName());
        //流程发起时间
        startDataPo.setFlowTakeDate(new Date());
        //获取登录人信息
        LoginUser loginUserInfo = getLoginUserInfo();
        //发起人ID
        startDataPo.setInitiatorId(loginUserInfo.getUserId().toString());
        //发起人Name
        startDataPo.setInitiatorName(loginUserInfo.getUsername());
        //流程状态
        startDataPo.setFlowStatus("0");
        //表单数据
        startDataPo.setFromData(startWorkDataDto.getFromData());

        //施工主要内容
        startDataPo.setConstructionContent(startWorkDataDto.getConstructionContent());
        //施工日期
        startDataPo.setConstructionDate(startWorkDataDto.getConstructionDate());
        //竣工日期
        startDataPo.setCompletionDate(startWorkDataDto.getCompletionDate());
        //施工单位
        startDataPo.setConstructionUnit(startWorkDataDto.getConstructionUnit());
        //工程施工开工申请单编号
        startDataPo.setConstructionNumber(startWorkDataDto.getConstructionNumber());
        //工程竣工验收单编号
        startDataPo.setCompletionNumber(startWorkDataDto.getCompletionNumber());
        startDataMapper.insert(startDataPo);


        List<WorkTicketDto> procedureList = startWorkDataDto.getProcedureList();
        //流程序号
        int count = 0;
        for (WorkTicketDto workTicketDto : procedureList) {

            //生成流程数据
            StartFlowDataPo startFlowDataPo = new StartFlowDataPo();
            //流程父ID 职位ID 职位名称  会有空指针的情况
            if (StringUtils.isNotBlank(workTicketDto.getFlowSchemeId())) {
                //开工流程流程父ID
                startFlowDataPo.setFlowId(workTicketDto.getFlowSchemeId());
            } else {
                startFlowDataPo.setFlowId("");
            }


            if (StringUtils.isNotBlank(workTicketDto.getPositionId())) {
                //职位ID
                startFlowDataPo.setPositionId(workTicketDto.getPositionId());
            } else {
                startFlowDataPo.setPositionId("");
            }
            if (StringUtils.isNotBlank(workTicketDto.getPositionName())) {
                //职位名称
                startFlowDataPo.setPositionName(workTicketDto.getPositionName());
            } else{
                //职位名称
                startFlowDataPo.setPositionName("");
            }

                //工作流流程ID
                //流程状态(将第一个设置为审批中)
                if (count == 0) {
                    startFlowDataPo.setFlowStatus("1");


                    List<String> toUser = new ArrayList();
                    //获取当前审批人，给审批人发送消息
                    if (workTicketDto.getApproverId() != null) {
                        toUser.add(workTicketDto.getApproverId());
                        WeChartBaseMessage msg = new WeChartBaseMessage();
                        String content = "有待您审批的流程——" + "" + ",请登陆系统后审批。";
                        msg.setContent(content);
                        msg.setPassword("hn@2022");
                        msg.setToUsers(org.apache.commons.lang3.StringUtils.join(toUser, ","));
                        try {
                            remoteMineInfoService.sendBaseMessage(msg);
                        } catch (Exception e) {
                            System.out.println("发送审批消息失败，flowID，审批人" +workTicketDto.getFlowSchemeId()+","+ workTicketDto.getApproverId());
                            e.printStackTrace();
                        }

                    }

                } else {
                    startFlowDataPo.setFlowStatus("0");
                }
            //流程序号
            startFlowDataPo.setFlowNumber(count);
            //流程序号++（+1）后面需要列表排序
            count++;
            //审批人ID
            startFlowDataPo.setApproverId(workTicketDto.getApproverId());
            //审批人名称
            startFlowDataPo.setApproverName(workTicketDto.getApproverName());
            //零星工程数据ID
            startFlowDataPo.setTicketDataId(startDataPo.getTickDataId());
            //选中的序号列表
            startFlowDataPo.setSerialNumbers(workTicketDto.getSerialNumbers());

            //表单数据
            startFlowDataPo.setJsonFrom(workTicketDto.getJsonFrom());

            startFlowDataMapper.insert(startFlowDataPo);

        }
        //processName  使用工作票名字+工作票ID

//        this.startProcess(workDataPo.getTickDataId(),
//                workDataPo.getTickName() + workDataPo.getWorkTicketId(),
//                loginUserInfo.getUserId() + "," + loginUserInfo.getUsername());
        // 使用Activiti开启工作流

        return true;
    }

    /**
     * 零星工程-分页条件查询
     * @param pageQuery
     * @param startWorkDataDto
     * @return
     */
    @Override
    public ResponsePage<StartWorkDataVo> projectPageList(PageQuery pageQuery, StartDataDto startWorkDataDto) {
        LambdaQueryWrapper<StartDataPo> queryWrapper = new LambdaQueryWrapper<>();
        //工程类别
        queryWrapper.eq(StringUtils.isNotBlank(startWorkDataDto.getTicketTypeId()),StartDataPo::getTicketTypeId, startWorkDataDto.getTicketTypeId());
        //工程名称
        queryWrapper.like(StringUtils.isNotBlank(startWorkDataDto.getStartTicketDataName()), StartDataPo::getTickDataName, startWorkDataDto.getStartTicketDataName());
        //施工日期
        queryWrapper.eq(startWorkDataDto.getConstructionDate() != null, StartDataPo::getConstructionDate, startWorkDataDto.getConstructionDate());
        //竣工日期
        queryWrapper.eq(startWorkDataDto.getCompletionDate() != null, StartDataPo::getCompletionDate, startWorkDataDto.getCompletionDate());
        //施工单位
        queryWrapper.like(StringUtils.isNotBlank(startWorkDataDto.getConstructionUnit()), StartDataPo::getConstructionUnit, startWorkDataDto.getConstructionUnit());
        //施工主要内容
        queryWrapper.like(StringUtils.isNotBlank(startWorkDataDto.getConstructionContent()), StartDataPo::getConstructionContent, startWorkDataDto.getConstructionContent());
        //工程施工开工申请单编号
        queryWrapper.like(StringUtils.isNotBlank(startWorkDataDto.getConstructionNumber()), StartDataPo::getConstructionNumber, startWorkDataDto.getConstructionNumber());
        //工程竣工验收单编号
        queryWrapper.like(StringUtils.isNotBlank(startWorkDataDto.getCompletionNumber()), StartDataPo::getCompletionNumber, startWorkDataDto.getCompletionNumber());
        queryWrapper.eq(StringUtils.isNotBlank(startWorkDataDto.getMineCode()), StartDataPo::getMineCode, startWorkDataDto.getMineCode());
        Page<StartDataPo> startDataPoPage = startDataMapper.selectPage(pageQuery.build(), queryWrapper);
        if (startDataPoPage.getRecords().isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        List<StartWorkDataVo> collect = startDataPoPage.getRecords().stream().map(t -> {
            StartWorkDataVo startWorkDataVo = new StartWorkDataVo();
            //零星工程管理主键ID
            startWorkDataVo.setTickDataId(t.getTickDataId());
            //零星工程名称
            startWorkDataVo.setStartTicketDataName(t.getTickDataName());
            //零星工程类型ID
            startWorkDataVo.setTicketTypeId(t.getTicketTypeId());
            startWorkDataVo.setTicketTypeName(t.getTicketTypeName());
            //施工主要内容
            startWorkDataVo.setConstructionContent(t.getConstructionContent());
            //施工日期
            startWorkDataVo.setConstructionDate(t.getConstructionDate());
            //竣工日期
            startWorkDataVo.setCompletionDate(t.getCompletionDate());
            //施工单位
            startWorkDataVo.setConstructionUnit(t.getConstructionUnit());
            //工程施工开工申请单编号
            startWorkDataVo.setConstructionNumber(t.getConstructionNumber());
            //工程竣工验收单编号
            startWorkDataVo.setCompletionNumber(t.getCompletionNumber());

            String flowStatus = t.getFlowStatus();
            //未完成
            if ("0".equals(flowStatus)) {
                StartFlowDataPo workFlowDataPos = startFlowDataMapper.selectOne(new LambdaQueryWrapper<StartFlowDataPo>().eq(StartFlowDataPo::getTicketDataId, t.getTickDataId()).eq(StartFlowDataPo::getFlowStatus, "1"));
                //工程状态 步骤状态
                startWorkDataVo.setTicketStart(workFlowDataPos.getFlowNumber() + "/" + startFlowDataMapper.selectCount(new LambdaQueryWrapper<StartFlowDataPo>().eq(StartFlowDataPo::getTicketDataId, t.getTickDataId())));


                //已完成
            } else if ("1".equals(flowStatus)) {
                startWorkDataVo.setTicketStart("已完成");
                //拒绝
            } else if ("2".equals(flowStatus)) {
                startWorkDataVo.setTicketStart("已拒绝");

            } else if ("3".equals(flowStatus)) {
                startWorkDataVo.setTicketStart("已撤销");
            } else {
                startWorkDataVo.setTicketStart("未知");
            }



            return startWorkDataVo;
        }).collect(Collectors.toList());


        return new ResponsePage<>(collect, startDataPoPage.getTotal());
    }

    /**
     * 完成审批
     * @param businessKey
     * @param is
     * @param approve
     * @param content
     * @return
     */
    @Override
    public Boolean accomplishApprove(String businessKey, Boolean is, String approve, String content) {

        //获取当前审批流程记录
        List<StartFlowDataPo> startFlowDataPoList = startFlowDataMapper.selectList(new LambdaQueryWrapper<StartFlowDataPo>().eq(StartFlowDataPo::getTicketDataId, businessKey));
        if (startFlowDataPoList.isEmpty()) {
            throw new HuaNengException(Constants.FAIL, "零星工程ID不存在");
        }
        //升序排序
        List<StartFlowDataPo> collect = startFlowDataPoList.stream().sorted(Comparator.comparing(StartFlowDataPo::getFlowNumber)).collect(Collectors.toList());

        for (int i = 0; i < collect.size(); i++) {
            //流程状态(0未完成，1，审批中，2已完成，3拒绝)
            String flowStatus = collect.get(i).getFlowStatus();
            //获取审批中的记录
            if ("1".equals(flowStatus)) {
                //获取当前记录的详细信息
                StartFlowDataPo startFlowDataPo = collect.get(i);

                //获取审批人
                String approverId = startFlowDataPo.getApproverId();
                String approverName = startFlowDataPo.getApproverName();

                //is为True 需要登录人审批
                if (is) {
                    //获取登录人信息
                    LoginUser loginUserInfo = getLoginUserInfo();
                    if (!approverId.equals(loginUserInfo.getUserId().toString())) {
                        throw new HuaNengException(Constants.FAIL, "登录人与审批人不是同一人");
                    }
                }
                if ("0".equals(approve)) {
                    //拒绝任务
                    StartDataPo startDataPo = startDataMapper.selectById(businessKey);
                    //该工作票设置为已拒绝
                    startDataPo.setFlowStatus("2");
                    startDataMapper.updateById(startDataPo);
                    //将该审批列表设置为拒绝
                    startFlowDataPo.setFlowStatus("3");
                    startFlowDataMapper.updateById(startFlowDataPo);
                    return true;
                }

                //获取登录人
                //使用完成审批
//                ProcessTaskResult processTaskResult = this.executeProcessTask(businessKey, Integer.parseInt(approve), content, approverId);
                //设置为审批已完成
                startFlowDataPo.setFlowStatus("2");
                startFlowDataMapper.updateById(startFlowDataPo);

                //判断此审批是否是最后一个
                //list 集合中
                if (i < collect.size() - 1) {
                    //将下一条审批设置为审批中
                    StartFlowDataPo workFlowDataPoNext = collect.get(i + 1);
                    workFlowDataPoNext.setFlowStatus("1");
                    startFlowDataMapper.updateById(workFlowDataPoNext);


                    List<String> toUser = new ArrayList();
                    //获取当前审批人，给审批人发送消息
                    if (workFlowDataPoNext.getApproverId() != null) {
                        toUser.add(workFlowDataPoNext.getApproverId());
                        WeChartBaseMessage msg = new WeChartBaseMessage();
                        String content1 = "有待您审批的流程——" + "" + ",请登陆系统后审批。";
                        msg.setContent(content1);
                        msg.setPassword("hn@2022");
                        msg.setToUsers(org.apache.commons.lang3.StringUtils.join(toUser, ","));
                        try {
                            remoteMineInfoService.sendBaseMessage(msg);
                        } catch (Exception e) {
                            System.out.println("发送审批消息失败，flowID，审批人" +workFlowDataPoNext.getFlowId()+","+ workFlowDataPoNext.getApproverId());
                            e.printStackTrace();
                        }

                    }


                } else {
                    //已经是最后一条记录
                    StartDataPo workDataPo = startDataMapper.selectById(businessKey);
                    workDataPo.setFlowStatus("1");
                    startDataMapper.updateById(workDataPo);
                }
                return true;

            }
        }
        return false;
    }

    /**
     * 撤销审批
     * @param id
     * @return
     */
    @Override
    public Boolean revocationApproveById(String id) {
        //登录ID
        LoginUser loginUserInfo = getLoginUserInfo();


        //零星工程管理ID
        StartDataPo startDataPo = startDataMapper.selectById(id);
        if (startDataPo == null) {
            throw new HuaNengException(Constants.FAIL, "零星工程管理ID" + id);
        }
        if (!loginUserInfo.getUserId().toString().equals(startDataPo.getInitiatorId())) {
            throw new HuaNengException(Constants.FAIL, "请使用发起人账号撤销审批");
        }

        LambdaQueryWrapper<StartFlowDataPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StartFlowDataPo::getTicketDataId, id);
        //获取流程表记录
        List<StartFlowDataPo> workFlowDataPos = startFlowDataMapper.selectList(wrapper);
        if (workFlowDataPos.isEmpty()) {
            throw new HuaNengException(Constants.FAIL, "流程为空");
        }
        for (StartFlowDataPo workFlowDataPo : workFlowDataPos) {
            //流程状态(0未完成，1，审批中，2已完成，3拒绝,4已撤销
            if ("1".equals(workFlowDataPo.getFlowStatus())) {
                workFlowDataPo.setFlowStatus("4");
                startFlowDataMapper.updateById(workFlowDataPo);
            }
            break;
        }
        //流程状态(0未完成,1已完成，2已拒绝，3已撤销
        startDataPo.setFlowStatus("3");
        startDataMapper.updateById(startDataPo);

        //撤销工作流
//        try {
//            revocation(id);
//        } catch (HuaNengException e) {
//            return false;
//        }
        return true;
    }

    /**
     * 根据零星工程DataID获取审批序号列表
     * @param id
     * @return
     */
    @Override
    public StartFlowDataDto approveDataById(String id) {
        //获取零星工程数据
        StartDataPo startDataPo = startDataMapper.selectById(id);
        if (startDataPo == null) {
            throw new HuaNengException(Constants.FAIL, "零星工程管理ID不存在" + id);
        }
        StartFlowDataDto startFlowDataDto = new StartFlowDataDto();
        //表单数据
        startFlowDataDto.setFromData(startDataPo.getFromData());
        //零星工程ID
        startFlowDataDto.setWorkTicketId(startDataPo.getTickDataId());
        LambdaQueryWrapper<StartFlowDataPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StartFlowDataPo::getTicketDataId, id);
        //获取记录
        List<StartFlowDataPo> workFlowDataPos = startFlowDataMapper.selectList(wrapper);
        startFlowDataDto.setProcedureList(workFlowDataPos);
        return startFlowDataDto;
    }

    /**
     * 零星工程-批量删除
     * @param idList
     * @return
     */
    @Override
    public Boolean projectDelete(List<String> idList) {
        int count = 0;
        for (String s : idList) {
            //删除零星工程
            int i = startDataMapper.deleteById(s);
            if (i == 0) {
                throw new HuaNengException(Constants.FAIL, "此ID删除失败" + s);
            }
            count += i;
            //删除零星工程流程记录
            startFlowDataMapper.delete(new LambdaQueryWrapper<StartFlowDataPo>().eq(StartFlowDataPo::getTicketDataId, s));

//            try {
//                //删除工作流
//                this.delete(s);
//            } catch (HuaNengException e) {
//                System.out.println("工作流删除出错");
//
//            }
        }
        if (count == idList.size()) {
            return true;
        }
        return false;
    }

    /**
     * 零星工程-From表单修改
     * @param fromUpdateDto
     * @return
     */
    @Override
    public Boolean fromUpdate(FromUpdateDto fromUpdateDto) {
        StartDataPo startDataPo = new StartDataPo();
        startDataPo.setTickDataId(fromUpdateDto.getId());
        startDataPo.setFromData(fromUpdateDto.getFromData());
        int i = startDataMapper.updateById(startDataPo);
        if (i > 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取我的审批列表
     */
    @Override
    public List<StartWorkDataVo> myApprove(String mineCode) {
        //获取登录人信息
        LoginUser loginUserInfo = getLoginUserInfo();
        //获取登录ID
        Long userId = loginUserInfo.getUserId();
        //获取所有工作票Data
        LambdaQueryWrapper<StartDataPo> startDataPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        startDataPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), StartDataPo::getMineCode, mineCode);
        List<StartDataPo> startDataPos = startDataMapper.selectList(startDataPoLambdaQueryWrapper);
        if (startDataPos.isEmpty()) {
            return new ArrayList<>();
        }
        List<StartWorkDataVo> approveVoList = new ArrayList<>();
        for (StartDataPo startDataPo : startDataPos) {
            //获取所有的工作票流程Data
            LambdaQueryWrapper<StartFlowDataPo> wrapper = new LambdaQueryWrapper<StartFlowDataPo>();
            //获取工作票数据id
            wrapper.eq(StartFlowDataPo::getTicketDataId, startDataPo.getTickDataId());
            //获取流程状态
            wrapper.eq(StartFlowDataPo::getFlowStatus, "1");
            wrapper.eq(StringUtils.isNotBlank(mineCode), StartFlowDataPo::getMineCode, mineCode);
            StartFlowDataPo startFlowDataPo = startFlowDataMapper.selectOne(wrapper);
            if (startFlowDataPo != null) {
                //有记录
                //获取审批人ID
                String approverId = startFlowDataPo.getApproverId();
                //判断登录人和审批人是同一个
                if (approverId.equals(userId.toString())) {

                    StartWorkDataVo startWorkDataVo = new StartWorkDataVo();
                    //零星工程管理主键ID
                    startWorkDataVo.setTickDataId(startDataPo.getTickDataId());
                    //零星工程名称
                    startWorkDataVo.setStartTicketDataName(startDataPo.getTickDataName());
                    //零星工程类型ID
                    startWorkDataVo.setTicketTypeId(startDataPo.getTicketTypeId());
                    startWorkDataVo.setTicketTypeName(startDataPo.getTicketTypeName());
                    //施工主要内容
                    startWorkDataVo.setConstructionContent(startDataPo.getConstructionContent());
                    //施工日期
                    startWorkDataVo.setConstructionDate(startDataPo.getConstructionDate());
                    //竣工日期
                    startWorkDataVo.setCompletionDate(startDataPo.getCompletionDate());
                    //施工单位
                    startWorkDataVo.setConstructionUnit(startDataPo.getConstructionUnit());
                    //工程施工开工申请单编号
                    startWorkDataVo.setConstructionNumber(startDataPo.getConstructionNumber());
                    //工程竣工验收单编号
                    startWorkDataVo.setCompletionNumber(startDataPo.getCompletionNumber());

                    String flowStatus = startDataPo.getFlowStatus();
                    //未完成
                    if ("0".equals(flowStatus)) {
                        StartFlowDataPo workFlowDataPos = startFlowDataMapper.selectOne(new LambdaQueryWrapper<StartFlowDataPo>().eq(StartFlowDataPo::getTicketDataId, startDataPo.getTickDataId()).eq(StartFlowDataPo::getFlowStatus, "1"));
                        //工程状态 步骤状态
                        startWorkDataVo.setTicketStart(workFlowDataPos.getFlowNumber() + "/" + startFlowDataMapper.selectCount(new LambdaQueryWrapper<StartFlowDataPo>().eq(StartFlowDataPo::getTicketDataId, startDataPo.getTickDataId())));


                        //已完成
                    } else if ("1".equals(flowStatus)) {
                        startWorkDataVo.setTicketStart("已完成");
                        //拒绝
                    } else if ("2".equals(flowStatus)) {
                        startWorkDataVo.setTicketStart("已拒绝");

                    } else if ("3".equals(flowStatus)) {
                        startWorkDataVo.setTicketStart("已撤销");
                    } else {
                        startWorkDataVo.setTicketStart("未知");
                    }

                    approveVoList.add(startWorkDataVo);
                }
            }

        }
        return approveVoList;
    }

    /**
     * 获取登录用户详细
     */
    private LoginUser getLoginUserInfo() {
        LoginUser loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            throw new HuaNengException(Constants.FAIL, "用户未登录,查询不到登录用户信息,无法录入发起人");
        }
        return loginUser;
    }

}
